﻿using EMoney.IStock.OAuth.Business;
using QConnectSDK;
using QConnectSDK.Context;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NetDimension.Weibo;
using EMoney.IStock.OAuth.Framework;
using EMoney.IStock.OAuth.Models;

namespace EMoney.IStock.OAuth.Web.Controllers
{
    public class OAuthController : Controller
    {
        public ActionResult QQ(string returnURL)
        {
            if (string.IsNullOrEmpty(Request["code"]))
            {
                var context = new QzoneContext();
                string state = Guid.NewGuid().ToString().Replace("-", "");
                Session["requeststate"] = state;
                string scope = "get_user_info,add_share,list_album,upload_pic,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idolist,add_idol,del_idol,add_one_blog,add_topic,get_tenpay_addr";

                string authenticationUrl = context.GetAuthorizationUrl(state, scope);
                authenticationUrl = string.Format(authenticationUrl, Server.UrlEncode(returnURL));

                return new RedirectResult(authenticationUrl);
            }
            else
            {
                var verifierCode = Request["code"];
                var state = Request["state"];
                var returnUrl = Request["returnUrl"];

                QOpenClient qzone = new QOpenClient(verifierCode, string.Empty);
                var currentUser = qzone.GetCurrentUser();

                string openID = qzone.OAuthToken.OpenId;

                if (returnUrl.IndexOf("?") > -1)
                {
                    returnUrl = string.Concat(returnUrl, "&code=", verifierCode);
                }
                else
                {
                    returnUrl = string.Concat(returnUrl, "?code=", verifierCode);
                }

                if (!string.IsNullOrEmpty(openID))
                {
                    returnUrl = string.Concat(returnUrl, "&openid=", openID);
                }

                if (currentUser != null && !string.IsNullOrEmpty(currentUser.Nickname))
                {
                    //returnUrl = string.Concat(returnUrl, "&nickname=",EncryptionUtil.Encrypt(currentUser.Nickname));
                }

                return Redirect(returnUrl);
            }
        }

        public ActionResult Sina(string returnURL)
        {
            var oauth = new NetDimension.Weibo.OAuth(ConfigHelper.SinaAppKey, ConfigHelper.SinaAppSecret, string.Format(ConfigHelper.SinaCallBackURI, Server.UrlEncode(returnURL)));

            if (Request["code"] == null)
            {
                var authenticationUrl = oauth.GetAuthorizeURL();
                return new RedirectResult(authenticationUrl);
            }
            else
            {
                string code = Request["code"];
                //string result = string.Empty;
                string returnUrl = Request["returnUrl"];

                if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(returnUrl))
                {
                    return UserIDAction(code, RegLoginType.Weibo, returnUrl);
                }

                ViewBag.Code = Request["code"];

                return View();
            }
        }

        public ActionResult qqshow()
        {
            var verifierCode = Request["code"];
            string result = string.Empty;

            try
            {
                QOpenClient qzone = new QOpenClient(verifierCode, string.Empty);
                var currentUser = qzone.GetCurrentUser();
                result = string.Concat("登录成功：" + currentUser.Nickname,"  OpenId:", qzone.OAuthToken.OpenId); //string.Concat("OpenId:", qzone.OAuthToken.OpenId, "  AccessToken:", qzone.OAuthToken.AccessToken,"  Nickname:", currentUser.Nickname, "  Figureurl:", currentUser.Figureurl);

                //return OAuthLoginAction("QQ", qzone.OAuthToken.OpenId, qzone.OAuthToken.AccessToken, currentUser.Nickname, returnURL, string.Empty);
            }
            catch (Exception ex)
            {
                result = string.Concat("异常：", ex.Message);
                //LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), "OAuth/QQ发生异常");

                //return Redirect(Url.Action("index", "home"));
            }

            ViewBag.Result = result;

            return View();
        }

        public ActionResult UserIDAction(string code, RegLoginType regLoginType, string returnUrl)
        {
            string uniqueNo = string.Empty;
            ReqLogin regLogin = new ReqLogin()
            {
                userType = regLoginType.GetHashCode(),
                account = code,
                clientType = 2
            };

            OAuthBll oAuthBll = new OAuthBll();

            LoginResult loginResult = oAuthBll.GetLoginResult(regLogin);

            if (loginResult != null && !string.IsNullOrEmpty(regLogin.OpenID))
            {
                uniqueNo = StringHelper.GetUniqueNo();

                if (!string.IsNullOrEmpty(uniqueNo))
                {
                    uniqueNo = uniqueNo.PadRight(16, '0');

                    JRPTCommCache.AddCache<string>(uniqueNo, loginResult.id.ToString(), 30);
                }

                string redirectUrl = string.Empty;

                if (returnUrl.IndexOf("?") > -1)
                {
                    redirectUrl = string.Concat(returnUrl, "&gid=", uniqueNo);
                }
                else
                {
                    redirectUrl = string.Concat(returnUrl, "?gid=", uniqueNo);
                }

                if (!string.IsNullOrEmpty(regLogin.OpenID))
                {
                    redirectUrl = string.Concat(redirectUrl, "&openid=", regLogin.OpenID);
                }
                return Redirect(redirectUrl);
            }

            return null;
        }

        /// <summary>
        /// 根据联合登录code返回登录信息
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        public ActionResult LoginByCode()
        {
            string ret = string.Empty;

            try
            {
                StreamReader reader = new StreamReader(Request.InputStream);

                string reqJson = reader.ReadToEnd();
                //string reqJson = "{\"userType\": 100,\"clientType\":1,\"sid\":106,\"ver\":20140624,\"md5\":\"7d49a26761c697300c4177447d3fa983\",\"hardware\":\"            6VD3\",\"account\":\"E89C25BC19AF0FC1AD9D8286AC1E05B3\",\"ext\":\"\"}";

                if (!string.IsNullOrEmpty(reqJson))
                {
                    ReqLogin reqLogin = JsonHelper.ToObject<ReqLogin>(reqJson);

                    if (reqLogin != null && !string.IsNullOrEmpty(reqLogin.account))
                    {
                        OAuthBll oAuthBll = new OAuthBll();

                        LoginResult loginResult = oAuthBll.GetLoginResult(reqLogin);

                        if (loginResult != null)
                        {
                            ret = JsonHelper.ToJson(loginResult);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "LoginByCode失败");
            }

            return Content(ret);
        }

        private ActionResult OAuthLoginAction(string userType, string bindUserID, string accessToken, string nick, string returnURL, string bindUserHeadImgUrl = null)
        {

            return null;
        }

        /// <summary>
        /// 绑定QQ号码
        /// </summary>
        /// <returns></returns>
        public string BindQQ()
        {
            int userid = 0;
            string reqCode = Request["code"];
            string reqUserID = Request["userid"];

            if (string.IsNullOrEmpty(reqCode) || string.IsNullOrEmpty(reqUserID))
            {
                return string.Empty;
            }

            if (!int.TryParse(reqUserID, out userid))
            {
                return string.Empty;
            }

            string ret = string.Empty;
            OAuthBll oAuthBll = new OAuthBll();

            string openID = oAuthBll.GetOpenID(reqCode);    //获取OpenID

            if (!string.IsNullOrEmpty(openID))
            {
                string qq = oAuthBll.GetUserQQByOpenID(openID); //获取QQ号码

                if (!string.IsNullOrEmpty(qq))
                {
                    ret = oAuthBll.BindMapUser(userid, qq, "100", openID);
                }
                else
                {
                    ret = "QQ号码为空";
                }
            }
            else
            {
                ret = "OpenID为空";
            }

            return ret;
        }

        public ActionResult Temp()
        {
            OAuthBll oAuthBll = new OAuthBll();

            oAuthBll.BindMapUser(21424, "115536016", "100", "7C4C83A438B67B842A566307AE33B105");

            //return Content(StringHelper.GetRequestTID());
            return null;
        }
    }
}
